<?php

namespace App\Support\Traits;


use Illuminate\Contracts\Pagination\CursorPaginator;
use Illuminate\Pagination\LengthAwarePaginator;


trait ServiceTrait
{

    /**
     * 分页查询
     * @param mixed|null $where
     * @param int $pageSize
     * @return LengthAwarePaginator
     */
    public function paginate(mixed $where = null, int $pageSize = 10): LengthAwarePaginator
    {
        return $this->model->when($this->auth, fn($q) => $q->where('user_id', auth()->id()))
            ->where($where)
            ->orderByDesc('id')
            ->paginate($pageSize);
    }

    /**
     * 游标分页查询
     * @param mixed|null $where
     * @param int $pageSize
     * @return CursorPaginator
     */
    public function cursor(mixed $where = null, int $pageSize = 10): CursorPaginator
    {
        return $this->model->when($this->auth, fn($q) => $q->where('user_id', auth()->id()))
            ->where($where)
            ->orderByDesc('id')
            ->cursorPaginate($pageSize);
    }

    /**
     * 创建
     * @param array $data
     */
    public function create(array $data)
    {
        return $this->model->create($data);
    }

    /**
     * 查询
     * @param $id
     */
    public function find($id)
    {
        return $this->model->find($id);
    }


    /**
     * 更新
     * @param $id
     * @param array $data
     */
    public function update($id, array $data)
    {
        $info = $this->find($id);
        if (!$info) {
            return false;
        }
        $info->update($data);

        return $info->refresh();
    }

    /**
     * 删除
     * @param $id
     * @return bool|null
     */
    public function delete($id): ?bool
    {
        return $this->find($id)?->delete();
    }

    /**
     * 批量删除
     * @param array $ids
     * @return int
     */
    public function destroy(array $ids): int
    {
        return $this->model->destroy($ids);
    }
}